package com.adtech.farmProducts.activities.fragment.dialog;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetDialogFragment;
import android.support.v4.app.DialogFragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.vise.log.ViseLog;
import com.adtech.common.Common;
import com.adtech.common.http.AsyncHttpPostFormData;
import com.adtech.common.http.AsyncHttpResponse;
import com.adtech.common.http.AsyncOkHttpClient;
import com.adtech.common.http.AsyncResponseHandler;
import com.adtech.common.model.RspModel;
import com.adtech.common.utils.AccountManagers;
import com.adtech.common.utils.MobileUtil;
import com.adtech.common.widgets.dialog.LoadingDialog;
import com.adtech.common.widgets.load.LoadFactory;
import com.adtech.common.widgets.load.core.LoadManager;
import com.adtech.common.widgets.load.view.AbsView;
import com.adtech.common.widgets.recycler.RecyclerViewAdapter;
import com.adtech.common.widgets.recycler.decoration.DividerItemDecoration;
import com.adtech.farmProducts.App;
import com.adtech.farmProducts.R;
import com.adtech.farmProducts.activities.activity.BillingInfoActivity;
import com.adtech.farmProducts.adapter.BillingTypeAdapter;
import com.adtech.farmProducts.model.BillingType;
import com.adtech.farmProducts.utils.Constants;
import com.adtech.farmProducts.utils.ToSDcard;
import com.adtech.farmProducts.widget.ClearTextIconEditText;
import com.adtech.farmProducts.widget.EmptyView;
import com.adtech.farmProducts.widget.ErrorView;
import com.adtech.farmProducts.widget.LoadingView;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;


/**
 * Descr:   创建订单
 */

public class CreateOrderDialogFragment extends DialogFragment implements View.OnClickListener, BillingTypeAdapter.onClickListener {

    private ClearTextIconEditText edPhone;
    private RecyclerView mRecyclerView;

    private LoadManager mLoadManager;
    private BillingTypeAdapter mAdapter;

    public static CreateOrderDialogFragment newInstance() {
        return new CreateOrderDialogFragment();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // 设置无标题栏
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 加载界面布局
        View view = inflater.inflate(R.layout.dialog_create_order, container, false);
        initView(view);
        setStyle(BottomSheetDialogFragment.STYLE_NORMAL, R.style.CustomBottomSheetDialogTheme);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initData();
    }

    private void initView(View view) {
        edPhone = view.findViewById(R.id.ed_phone);
        mRecyclerView = view.findViewById(R.id.recycler_view);
        view.findViewById(R.id.next_step).setOnClickListener(this);
        edPhone.setMaxLength(edPhone, 11, "手机号");
    }

    private void initData() {
        mLoadManager = LoadFactory.getInstance().register(edPhone, new AbsView.OnReloadListener() {
            @Override
            public void onReload(View view) {
                mLoadManager.showStateView(LoadingView.class);
                webBillingList();
            }
        });
        initList();
        webBillingList();
    }

    /**
     * 初始化列表
     */
    private void initList() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(getContext(),
                DividerItemDecoration.VERTICAL, R.drawable.shape_divider_line, 16, false));

        mAdapter = new BillingTypeAdapter(new RecyclerViewAdapter.AdapterListenerImpl<BillingType>() {
        });
        mAdapter.setBillingOnClickListener(this);
        mRecyclerView.setAdapter(mAdapter);
    }


    /**
     * 获取计价列表
     */
    private void webBillingList() {
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("driver_id", AccountManagers.getUserId());
        okHttpClient.post(Common.Constant.API_IP + "api/Driver/queryDriverPriceConfigList", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                mLoadManager.showStateView(ErrorView.class);
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                Type type = new TypeToken<RspModel<List<BillingType>>>() {
                }.getType();
                RspModel<List<BillingType>> rspModel = getAnalysisBase(mLoadManager, response, type, "获取计价列表");
                if (rspModel == null) {
                    return;
                }
                switch (rspModel.getCode()) {
                    case 200:
                        if (rspModel.getData() != null && !"[]".equals(rspModel.getData().toString())) {
                            mAdapter.replace(rspModel.getData());
                        } else {
                            mLoadManager.showStateView(EmptyView.class);
                        }
                        break;
                    default:
                        App.getInstance().showMessage(rspModel.getMessage());
                        break;
                }
            }
        });
    }

    /**
     * 创建订单
     */
    private void webCreateOrder(String phone, String province, String city) {
        loadingDialogShow(true);
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("driver_id", AccountManagers.getUserId());
        asyncHttpPostFormData.addFormData("province_name", province);
        asyncHttpPostFormData.addFormData("city_name", city);
        asyncHttpPostFormData.addFormData("pricetemp_id", billingId);
        asyncHttpPostFormData.addFormData("cusphone", phone);
        okHttpClient.post(Common.Constant.API_IP + "api/Order/createLocalOrder", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                e.printStackTrace();
                onDismiss();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<String>>() {
                }.getType();
                RspModel<String> rspModel = getAnalysis(response, type, "创建订单");
                if (rspModel == null) {
                    return;
                }
                try {
                    if (rspModel.getCode() == 200) {
                        if (rspModel.isStatus()) {
                            close();
                        } else {
                            if (rspModel.getMessage().contains("到期") || rspModel.getMessage().contains("无")) {
                                dialogVip(rspModel.getMessage());
                            } else {
                                App.getInstance().showMessage(rspModel.getMessage());
                            }
                        }
                    } else {
                        App.getInstance().showMessage(rspModel.getMessage());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 司机状态
     */
    private void dialogVip(String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("提示");
        builder.setCancelable(false);
        builder.setMessage(message);
        builder.setNegativeButton("充会员", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    private LoadingDialog loadingDialog;

    public void loadingDialogShow(boolean canBack) {
        if (loadingDialog != null) {
            loadingDialog.cancel();
        } else {
            loadingDialog = new LoadingDialog(getActivity());
        }
        loadingDialog.show(canBack, R.layout.layout_state_loading);
    }

    public void onDismiss() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
            loadingDialog = null;
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        Window window = getDialog().getWindow();
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        layoutParams.gravity = Gravity.BOTTOM;
        window.setAttributes(layoutParams);

        //设置背景半透明
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        getDialog().getWindow().setLayout(dm.widthPixels, getDialog().getWindow().getAttributes().height);
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    }

    /**
     * 关闭dialog
     */
    private void close() {
        if (getDialog() != null && getDialog().isShowing()) {
            dismiss();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.next_step:
                String phone = String.valueOf(edPhone.getText());
                if (!TextUtils.isEmpty(phone)) {
                    if (!MobileUtil.checkMobile(phone)) {
                        App.getInstance().showMessage("请输入正确的手机号！");
                        return;
                    }
                }
                for (BillingType billingType:mAdapter.getDataList()) {
                    if(billingType.getIsdefault()==1){
                        billingId=billingType.getTemp_id();
                    }
                }
                if (billingId == null || "".equals(billingId)) {
                    App.getInstance().showMessage("请选择计价模式！");
                    return;
                }
                if (Constants.getLocation() != null) {
                    webCreateOrder(phone, Constants.getLocation().getProvince(), Constants.getLocation().getCity());
                } else {
                    App.getInstance().showMessage(getResources().getString(R.string.none_location));
                    ToSDcard.saveInfoToFile(ToSDcard.getLocationString(Constants.getLocation()));
                }
                break;
        }
    }

    private String billingId;

    /**
     * 数据解析
     *
     * @param response 数据源
     * @param type     class
     * @param log      log
     * @param <T>      泛型
     * @return 结果
     */
    public <T> RspModel<T> getAnalysisBase(LoadManager mLoadManager, AsyncHttpResponse response, Type type, String log) {
        ViseLog.d(response.toString());
        switch (response.getCode()) {
            case 200:
                try {
                    RspModel<T> rspModel = new Gson().fromJson(response.getBody(), type);
                    ViseLog.e(log + rspModel.toString());
                    switch (rspModel.getCode()) {
                        case 200:
                            mLoadManager.showSuccessView();
                            return rspModel;
                        default:
                            App.getInstance().showMessage(rspModel.getMessage());
                            mLoadManager.showStateView(EmptyView.class);
                            break;
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                    mLoadManager.showStateView(ErrorView.class);
                }
                break;
            default:
                mLoadManager.showStateView(EmptyView.class);
                break;
        }
        return null;
    }

    public <T> RspModel<T> getAnalysis(AsyncHttpResponse response, Type type, String log) {
        ViseLog.d(getClass().getSimpleName() + ":" + response.toString());
        switch (response.getCode()) {
            case 200:
                try {
                    RspModel<T> rspModel = new Gson().fromJson(response.getBody(), type);
                    ViseLog.e(log + rspModel.toString());
                    return rspModel;
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }
                break;
            default:
                App.getInstance().showMessage(getString(R.string.service_error));
                break;
        }
        return null;
    }

    /**
     * 隐藏软键盘
     **/
    public void hideKeyboard() {
        View view = getActivity().getWindow().peekDecorView();
        if (view != null) {
            InputMethodManager inputmanger = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode==200 && resultCode==100){
            webBillingList();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onClickButton(int value, int position, BillingType data) {
        switch (value) {
            case 1:
                for (BillingType type : mAdapter.getDataList()) {
                    type.setIsdefault(0);
                }
                mAdapter.getDataList().get(position).setIsdefault(1);
                mAdapter.notifyDataSetChanged();// 刷新显示
                hideKeyboard();
                break;
            case 2:
                Intent intent = new Intent(getContext(), BillingInfoActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("BillingType", data);
                intent.putExtras(bundle);
                startActivityForResult(intent,200);
                break;
        }
    }
}
